/** 身份读卡器对接 */

import {ElMessage} from 'element-plus'
import {downLacolFile} from './common'
import {showMessageBox} from './element'

//身份证读卡器型号 华旭GC
export enum IdCardReaderType {
  HXGC
}

export interface IdCardData {
  //证件号
  idNum: string
  //姓名
  name: string
  //性别
  sex: string
  //民族
  nation: string
  //证件开始日期
  effDate: string
  //证件结束日期
  expDate: string
  //证件类别
  cardSign: string
  //住址
  address: string
  //照片
  photo: string
}

//下载消息
export const showIdReaderDownMeaasage = (message: string, title: string) => {
  showMessageBox(message, {title: title, mesageType: 'base'})
    .then(() => {
      //版本过低
      downLacolFile('华旭读卡器插件.rar', '/resources/华旭读卡器插件.rar')
    })
    .catch(() => {
      //
    })
}

class BaseIdCardReader {
  protected idCardData?: IdCardData
  public getIdCardData(): IdCardData | undefined {
    if (this.idCardData) return {...this.idCardData}
    else return undefined
  }
  public clear() {
    this.idCardData = undefined
  }
}

enum HXGCReadStatus {
  SUCCESS,
  OTHERS
}
export interface HXGCData {
  //状态 0为成功 其他为失败
  result: HXGCReadStatus
  //证件号
  ID: string
  //名称
  Name: string
  //性别
  Sex: string
  //民族
  Ethnicity: string
  //证件开始日期
  ValidBeg: string
  //证件结束日期
  ValidEnd: string
  //证件类别
  CardSign: string
  //住址
  Address: string
  //照片
  photo: string
}

export enum ReadErrorType {
  READ_FAIL,
  CONNECT_ERROR,
  CONNECT_CLOSE
}
//华旭身份证读卡器
export class HXGCReader extends BaseIdCardReader {
  //websocket连接设置
  private webSocket?: WebSocket
  private baseUrl = '127.0.0.1'
  private basePort = '17171'
  //是否正常关闭
  private normalClose = false
  //华旭读取的数据结构
  private readerData?: HXGCData
  private get Url() {
    return `ws://${this.baseUrl}:${this.basePort}`
  }

  private mapData() {
    if (!this.readerData) return
    const {ID, Name, Sex, Ethnicity, ValidBeg, ValidEnd, CardSign, Address, photo} = this.readerData
    const photoData = 'data:image/jpeg;base64,' + photo
    this.idCardData = {idNum: ID, name: Name, sex: Sex, nation: Ethnicity, effDate: ValidBeg, expDate: ValidEnd, cardSign: CardSign, address: Address, photo: photoData}
  }

  public readIdCard(): Promise<IdCardData> {
    return new Promise<IdCardData>((resolve, reject) => {
      this.clear()
      if (this.webSocket && (this.webSocket.readyState === WebSocket.OPEN || this.webSocket.readyState === WebSocket.CONNECTING)) {
        this.webSocket.close()
      }
      this.normalClose = false
      this.webSocket = new WebSocket(this.Url)
      this.webSocket.onopen = () => {
        //发送读卡请求
        this.webSocket?.send('readcard')
      }
      this.webSocket.onmessage = (evt: MessageEvent) => {
        this.webSocket?.close()
        this.normalClose = true
        this.readerData = JSON.parse(evt.data)
        if (this.readerData?.result === HXGCReadStatus.SUCCESS) {
          this.mapData()
          resolve(this.getIdCardData() as IdCardData)
        } else {
          ElMessage.error('身份证信息读取失败!')
          reject(ReadErrorType.READ_FAIL)
        }
      }
      this.webSocket.onerror = () => {
        console.log('华旭连接出错')
        showIdReaderDownMeaasage('身份证读卡器控件加载出错,请下载并安装控件;安装完成后请刷新页面重试!', '安装')
        reject(ReadErrorType.CONNECT_ERROR)
      }
      this.webSocket.onclose = () => {
        console.log('华旭连接已关闭')
        if (!this.normalClose) {
          reject(ReadErrorType.CONNECT_CLOSE)
        }
      }
    })
  }

  public clear() {
    super.clear()
    this.readerData = undefined
  }
}